package my.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.mvc.ManagementServletContext;
import org.springframework.boot.autoconfigure.h2.H2ConsoleProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class URLSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    ManagementServletContext managementServletContext;
    @Autowired
    H2ConsoleProperties      h2ConsoleProperties;



    @Override
    protected void configure(HttpSecurity pHttp) throws Exception {
        String contextPath = this.managementServletContext.getContextPath();
        String h2ConsolePath = h2ConsoleProperties.getPath();
        // ACTUATOR
        pHttp.authorizeRequests()
            .antMatchers(toAntPath(contextPath), toAntPath(h2ConsolePath)).hasAnyRole("admin")
            .and().httpBasic()
            .and().headers().frameOptions().sameOrigin()
            .and().csrf().disable();
            // .and().csrf().ignoringAntMatchers(toAntPath(h2ConsolePath))
    }



    @Override
    protected void configure(AuthenticationManagerBuilder pAuth) throws Exception {
        // super.configure(pAuth);
        pAuth.inMemoryAuthentication()
            .withUser("admin").password("admin").roles("admin");
    }



    String toAntPath(String pPath) {
        return (pPath.endsWith("/") ? pPath + "**" : pPath + "/**");
    }
}
